package com.blogs.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.blogs.entity.Feed;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.TbBlogLine;
import com.blogs.ui.OfflineDownloadActivity;
import com.cnblogs.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;

public class OffLineDLService extends Service {
	// private static volatile int serviceCount = 0;
	private static final int NOTIFICATION_ID = 0x12;
	private NotificationManager nm;
	private Notification baseNF;

	private TbBlogLine db;
	private int pagesize;
	private ArrayList<String> dllist;
	private ArrayList<String> dllist_name;
	private int channelsize;

	private int curItem = 0;
	private int AllLenth;
	private boolean IsRunIng = false;
	private int _progress = 0;
	private Thread t;

	private DBSharedPreferences sp;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		this.InitNotification();
		sp = new DBSharedPreferences(this);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent != null && intent.getIntExtra("stop", 0) == 1) {
			IsRunIng = false;
			if (t != null)
				t.interrupt();
			stopTheServer();
		} else if (intent != null && !IsRunIng) {
			IsRunIng = true;
			curItem = 0;
			baseNF.tickerText = "博文离线下载";
			pagesize = intent.getIntExtra("pagesize", 0);
			dllist = intent.getStringArrayListExtra("dllist");
			dllist_name = intent.getStringArrayListExtra("dllist_name");
			channelsize = intent.getIntExtra("channelsize", 0);
			AllLenth = channelsize * pagesize * 20;
			DownLoad downLoad = new DownLoad();
			t = new Thread(downLoad);
			t.start();
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("OffLineDLServiceExit", "OffLineDLServiceExit");
		nm.cancel(NOTIFICATION_ID);
	}

	private void InitNotification() {
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		baseNF = new Notification(R.drawable.off_line_down, "博文离线下载", System.currentTimeMillis());
		baseNF.flags = Notification.FLAG_AUTO_CANCEL;
		// FLAG_ONGOING_EVENT
		baseNF.contentView = new RemoteViews(this.getPackageName(), R.layout.download_notification_layout);
		baseNF.contentView.setProgressBar(R.id.download_notification_pb, 100, 0, false);
		baseNF.contentView.setTextViewText(R.id.download_notification_tv, "进度" + _progress + "%");
		baseNF.contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, OfflineDownloadActivity.class), 0);

	}

	private void setProgess(int pro) {
		baseNF.contentView.setProgressBar(R.id.download_notification_pb, 100, pro, false);
		baseNF.contentView.setTextViewText(R.id.download_notification_tv, "进度" + pro + "%");
		nm.notify(NOTIFICATION_ID, baseNF);
		// nm.cancel(NOTIFICATION_ID);
	}

	private void SendMsg(int what, int arg1) {
		Message message = new Message();
		message.what = what;
		message.arg1 = arg1;
		downLoadHandler.sendMessage(message);
	}

	private void stopTheServer() {
		this.stopSelf();
		Log.i("OffLineDLServiceExit", "OffLineDLServicestopSelf");
		nm.cancel(NOTIFICATION_ID);
	}

	class DownLoad implements Runnable {
		public void run() {
			// TODO Auto-generated method stub
			setProgess(0);
			for (int i = 0; i < channelsize && IsRunIng; i++) {
				db = new TbBlogLine(OffLineDLService.this, dllist.get(i).replace("/", "%2F"));
				db.Delete();
				db.DbClose();
				for (int j = 0; j < pagesize && IsRunIng; j++) {
					ArrayList<Feed> feeds = new OffLineGetTimeLine(OffLineDLService.this, dllist.get(i), j + 1)
							.loadData();
					if (feeds == null)
						break;
					Date now = new Date();
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					sp.SetStrVarValue(dllist_name.get(i), df.format(now));
					for (int k = 0; k < feeds.size() && IsRunIng; k++) {
						new OffLineGetBlogDetail(OffLineDLService.this, feeds.get(k).blog_id).loadData();
						curItem++;
						_progress = (int) (((float) curItem / AllLenth * 100));
						Log.i("_progress", _progress + "");
						SendMsg(0, _progress);
						Log.i("DownLoad", curItem + "");
					}
				}
			}
			baseNF.tickerText = "博文下载完成";
			SendMsg(1, 100);
			IsRunIng = false;
			stopTheServer();
			// ok;

		}
	}

	private Handler downLoadHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			// setNotification(R.drawable.queue_icon_send, "下载中", msg.arg1+"");
			Intent intent = new Intent("OfflinePbReceiver");
			setProgess(msg.arg1);
			if (msg.what == 1) {
				intent.putExtra("finish", 1);
			} else {
				intent.putExtra("finish", 0);
			}

			intent.putExtra("progress", msg.arg1);
			sendBroadcast(intent);// 发送广播
		};
	};
}
